package com.ygq.controller;

import DO.StudentDO;
import DTO.EditStudentPasswordDTO;
import DTO.StudentLoginDTO;
import VO.StudentLoginVO;
import constant.CodeConstant;
import constant.JwtClaimsConstant;
import constant.MessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import result.Result;
import lombok.extern.slf4j.Slf4j;
import com.ygq.StudentService;
import utils.JwtUtils;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/student")
@Slf4j
public class StudentLoginController {

    @Autowired
    private StudentService studentService;

    /**
     * 学生登录接口
     * @param studentLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<StudentLoginVO> login(@RequestBody StudentLoginDTO studentLoginDTO){
        log.info("学号为"+studentLoginDTO.getStudentNumber()+"的学生登录。密码为："+studentLoginDTO.getPassword());
        StudentDO studentDo = studentService.getById(studentLoginDTO);
        if (studentDo==null){
            return Result.error(MessageConstant.PASSWORD_ERROR, CodeConstant.PASSWORD_ERROR);
        }
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ID, studentDo.getId());//存入该操作者的用户id
        claims.put(JwtClaimsConstant.OPERATOR, JwtClaimsConstant.STUDENT);//存入该操作者的人物性质

        claims.put("id", studentDo.getId());//存入该操作者的id

        String token = JwtUtils.generateJwt(claims);

        StudentLoginVO studentLoginVO = new StudentLoginVO();
        studentLoginVO.setToken(token);
        studentLoginVO.setUsername(studentDo.getUsername());
        studentLoginVO.setStudentNumber(studentDo.getStudentNumber());
        studentLoginVO.setId(studentDo.getId());
        studentLoginVO.setClassId(studentDo.getClassId());
        return Result.success(studentLoginVO);
    }

    /**
     * 修改学生密码
     * @param editStudentPasswordDTO
     * @return
     */
    @PostMapping("/editPassword")
    public Result<String> EditStudentPassword(@RequestBody EditStudentPasswordDTO editStudentPasswordDTO){
        String password = studentService.getPasswordById(editStudentPasswordDTO.getId());
        if (!password.equals(editStudentPasswordDTO.getOldPassword())){
            return Result.error(MessageConstant.PASSWORD_ERROR, CodeConstant.PASSWORD_ERROR);
        }
        studentService.editPassword(editStudentPasswordDTO);
        return Result.success("ok");
    }
}
